<template>
  <div class="content">
    <x-card message="" :width="60" :height="height1" style="margin: auto">
      <div class="top">
        <h2>个人信息</h2>
        <a-button
          v-if="!isEditing"
          type="primary"
          @click="startEditing"
          style="background: #1890ff; border-color: #1890ff"
          v-checkpermission:foo.bar="'sysset_personinfo_edit'"
          >编辑</a-button
        >
      </div>

      <a-form
        :model="userInfo"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 14 }"
        class="info-form"
      >
        <a-form-item label="用户名" required>
          <span v-if="!isEditing">{{ userInfo.username }}</span>
          <a-input v-else v-model:value="userInfo.username" />
        </a-form-item>

        <a-form-item label="真实姓名:" required>
          <span v-if="!isEditing">{{ userInfo.truename }}</span>
          <a-input v-else v-model:value="userInfo.truename" />
        </a-form-item>

        <a-form-item label="手机号码:" required>
          <span v-if="!isEditing">{{ userInfo.phone }}</span>
          <a-input v-else v-model:value="userInfo.phone" />
        </a-form-item>

        <a-form-item label="邮箱">
          <span v-if="!isEditing">{{ userInfo.email }}</span>
          <a-input v-else v-model:value="userInfo.email" />
        </a-form-item>

        <a-form-item label="修改密码">
          <a-button type="link" @click="showChangePassword" v-checkpermission:foo.bar="'sysset_personinfo_editPwd'"
            >点击修改密码</a-button
          >
        </a-form-item>

        <div v-if="isEditing" class="form-actions">
          <a-button type="primary" @click="saveInfo" style="margin-right: 10px"
            >保存</a-button
          >
          <a-button @click="cancelEditing">取消</a-button>
        </div>
      </a-form>
    </x-card>

    <!-- 修改密码模态框 -->
    <a-modal
      v-model:visible="changePasswordVisible"
      title="修改密码"
      @ok="handleChangePassword"
      @cancel="cancelChangePassword"
    >
      <a-form
        :model="passwordForm"
        :rules="passwordRules"
        ref="passwordFormRef"
      >
        <a-form-item label="旧密码" name="oldPassword">
          <a-input-password v-model:value="passwordForm.oldPassword" />
        </a-form-item>
        <a-form-item label="新密码" name="newPassword">
          <a-input-password v-model:value="passwordForm.newPassword" />
        </a-form-item>
        <a-form-item label="确认密码" name="confirmPassword">
          <a-input-password v-model:value="passwordForm.confirmPassword" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
  
  <script setup lang="ts">
import XCard from "./XCard.vue";
import { ref, reactive, onMounted } from "vue";
import http from "../routerutils/http";
import { message } from "ant-design-vue";
import { useStore } from "vuex";
const store = useStore()
const userPermiss_vuex = store.state.userPermiss
// 创建一个自定义指令，来统一处理权限存在与否
const vCheckpermission = {
  mounted: (el:any, binding:any) => {
    if (!userPermiss_vuex.includes(binding.value)) {
      // 移除元素
      el.parentNode?.removeChild(el);
    }
    console.log(el, binding);
    // el.classList.add("is-highlight");
  },
};

const message1 = ref<string>("个人信息");
const height1 = ref<string>("500px");
const isEditing = ref(false);
const changePasswordVisible = ref(false);

// 用户信息
const userInfo = reactive({
  username: "",
  truename: "",
  phone: "",
  email: "",
});

// 密码表单
const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 密码验证规则
const passwordRules = {
  oldPassword: [{ required: true, message: "请输入旧密码" }],
  newPassword: [
    { required: true, message: "请输入新密码" },
    { min: 6, message: "密码长度至少6位" },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码" },
    ({ getFieldValue }) => ({
      validator(item: any, value: any) {
        if (!value || getFieldValue("newPassword") === value) {
          return Promise.resolve();
        }
        return Promise.reject("两次输入的密码不一致");
      },
    }),
  ],
};

// 获取个人信息
const getInfo = async () => {
  try {
    const res = await http.get("/api/users/per_edit_get");
    Object.assign(userInfo, res.data.results[0]);
    console.log("个人信息：", res);
  } catch (error) {
    console.log("个人信息获取失败", error);
    message.error("获取个人信息失败");
  }
};

// 开始编辑
const startEditing = () => {
  isEditing.value = true;
};

// 取消编辑
const cancelEditing = () => {
  isEditing.value = false;
  getInfo(); // 重新获取原始数据
};

// 保存信息
const saveInfo = async () => {
  try {
    await http.post("/api/users/per_edit_set", userInfo);
    message.success("个人信息保存成功");
    isEditing.value = false;
  } catch (error:any) {
    console.log("保存失败", error);
    message.error(error.response.data.msg);
  }
};

// 显示修改密码对话框
const showChangePassword = () => {
  changePasswordVisible.value = true;
};

// 取消修改密码
const cancelChangePassword = () => {
  changePasswordVisible.value = false;
  Object.assign(passwordForm, {
    oldPassword: "",
    newPassword: "",
    confirmPassword: "",
  });
};

// 处理修改密码
const handleChangePassword = async () => {
  try {
    const res = await http.post("/api/users/change_pwd", passwordForm);
    console.log(res)
    message.success(res.data.msg);
    cancelChangePassword();
  } catch (error:any) {
    console.log("修改密码失败", error.response.data.msg);
    message.error(error.response.data.msg);
  }
};

onMounted(() => {
  getInfo();
});
</script>
  
  <style scoped>
.content {
  margin: auto;
}

.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.info-form {
  margin-top: 20px;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}
</style>